package com.alianzamedica.view;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Doctor;
import com.alianzamedica.tools.Enviroment;

/**
 * @author Carlos
 * 
 */
@SuppressWarnings("serial")
public class LoginForm extends ActionForm {

	private String email;
	private String password;

	/**
	 * regresa el email.
	 * 
	 * @return email.
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * setea el email.
	 * 
	 * @param email
	 *            email.
	 */
	public void setEmail(String email) {
		this.email = email;
	}

	/**
	 * password del sistema.
	 * 
	 * @return password.
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * setea el password del sistema.
	 * 
	 * @param password
	 *            password.
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * obtiene el doctor.
	 * 
	 * @return doctor.
	 */
	public Doctor getDoctor() {
		Doctor d = new Doctor();
		d.setEmail(email);
		d.setPassword(password);
		return d;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();
		try {
			Enviroment env = Enviroment.getInstance();
			Document doc = env.getDocument();
			ObjectSearch search = new ObjectSearch(doc,
					"com.alianzamedica.connection.ConnectionImpl");
			Doctor d = this.getDoctor();
			Iterator<Doctor> iterator = search.searchObjects(d).iterator();
			@SuppressWarnings("unused")
			Doctor doctor = null;
			if (iterator.hasNext()) {
				doctor = (Doctor) iterator.next();
			} else {
				errors.add("nolog", new ActionMessage(
						"nombre de usuario o contraseña invalidos"));
			}

			if (errors.size() > 0) {
				request.setAttribute("doctor", d);
				request.setAttribute("errors", errors);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return errors;
	}

}
